//
//  ISAACRegistController.m
//  FireBird
//
//  Created by Isaac on 2018/5/2.
//  Copyright © 2018年 Isaac. All rights reserved.
//

#import "ISAACRegistController.h"
#import "ISAACProtocalController.h"
#import "ISAACRegistPSWController.h"
@interface ISAACRegistController ()
@property (nonatomic, strong)UITextField *accountText;
@property (nonatomic, strong)UITextField *pswText;

@end

@implementation ISAACRegistController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self addTitleViewWithTitle:@"注册"];
    
    [self setupViews];
    
}
- (void)setupViews {
    
    self.accountText = [MyControlUilt createTextFieldWithFrame:CGRectMake(LEFTSPACE, 120, SCREEN_WIDTH-LEFTSPACE*2, 30) Title:@"输入手机号" TextColor:kTextColorTwo SuperView:self.view Font:FONT14 BackColor:kBackGColor];
    
    self.pswText = [MyControlUilt createTextFieldWithFrame:CGRectMake(LEFTSPACE, CGRectGetMaxY(_accountText.frame), SCREEN_WIDTH-LEFTSPACE*2-100, 30) Title:@"输入验证码" TextColor:kTextColorTwo SuperView:self.view Font:FONT14 BackColor:kBackGColor];
    
    UIButton *getVericodeBtn = [MyControlUilt createButtonWithFrame:CGRectMake(SCREEN_WIDTH-LEFTSPACE-100, CGRectGetMinY(_pswText.frame), 100, 30) Title:@"获取验证码" TiTleColor:kRedColor SuperView:self.view Font:FONT14 BackColor:kBackGColor];
    [getVericodeBtn addTarget:self action:@selector(handleGetVerifyCode:) forControlEvents:UIControlEventTouchUpInside];

    UILabel *tipLabel = [MyControlUilt createLabelWithFrame:CGRectMake(LEFTSPACE, CGRectGetMaxY(_pswText.frame)+20, SCREEN_WIDTH-LEFTSPACE *2, 20) labelText:@"" backColor:nil Font:FONT13 TextColor:kTextColorTwo SuperView:self.view];

    [tipLabel setAttributedText:[[WSMTools wsmTool] getAttributedString:@"已有账号？去登录" Color:kPriceColor begin:6 end:2 LineSpace:0 IsCenter:NO Font:13] ];
    tipLabel.textAlignment = NSTextAlignmentCenter;
    tipLabel.userInteractionEnabled = YES;
    [tipLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handlePushColumn:)]];
    
    UIButton *confirmBtn = [MyControlUilt createButtonWithFrame:CGRectMake((SCREEN_WIDTH-150)/2.0, CGRectGetMaxY(tipLabel.frame)+20, 150, 42) Title:@"下一步" TiTleColor:kWhiteColor SuperView:self.view Font:FONT14 BackColor:kRedColor];
    confirmBtn.layer.masksToBounds = YES;
    confirmBtn.layer.cornerRadius = 21;
    [confirmBtn addTarget:self action:@selector(handleConfirmLogin:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel *tipDownLabel = [MyControlUilt createLabelWithFrame:CGRectMake(LEFTSPACE, SCREEN_HEIGHT-100, SCREEN_WIDTH-LEFTSPACE *2, 20) labelText:@"" backColor:nil Font:FONT13 TextColor:kTextColorTwo SuperView:self.view];
    
    [tipDownLabel setAttributedText:[[WSMTools wsmTool] getAttributedString:@"点击下一步代表已阅读并同意你用户注册协议" Color:kPriceColor begin:16 end:4 LineSpace:0 IsCenter:NO Font:13] ];
    tipDownLabel.textAlignment = NSTextAlignmentCenter;
    tipDownLabel.userInteractionEnabled = YES;
    [tipDownLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleProtocal:)]];
    
    
}
- (void)handleGetVerifyCode:(UIButton *)sender {
    if (_accountText.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        return;
    }
    if (![TTConfig validateMobile:_accountText.text]) {
        [SVProgressHUD showErrorWithStatus:@"手机号不正确"];
        return;
    }
    __block int timeout=60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [sender setTitle:@"发送验证码" forState:UIControlStateNormal];
                sender.userInteractionEnabled = YES;
            });
        }else{
            NSInteger seconds = timeout % 61;
            NSString *strTime = [NSString stringWithFormat:@"%ld", (long)seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //NSLog(@"____%@",strTime);
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [sender setTitle:[NSString stringWithFormat:@"%@秒",strTime] forState:UIControlStateNormal];
                [UIView commitAnimations];
                sender.userInteractionEnabled = NO;
            });
            timeout--;
        }
        
    });
    dispatch_resume(_timer);
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"phone"] = _accountText.text;
    param[@"type"] = @(1);
    
    //  去获取验证码
    __weak typeof(self) weakself = self;
    [TTServerTool postDictionaryResult:API_sms_send param:param isNeedToken:YES complete:^(BOOL network, TTPublicResult * result, NSError * error) {
        
        if (network) {
            
            if (result) {
                
                if([result.ErrorCode isEqualToString:@"0"]){
                    [weakself.pswText becomeFirstResponder];
                    
                    
                }else{
                    [SVProgressHUD showErrorWithStatus:result.ErrorMsg];
                    //倒计时结束，关闭
                    dispatch_source_cancel(_timer);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //设置界面的按钮显示 根据自己需求设置
                        [sender setTitle:@"发送验证码" forState:UIControlStateNormal];
                        sender.userInteractionEnabled = YES;
                    });
                }
                
            }else{
                [SVProgressHUD showErrorWithStatus:@"暂无数据"];
                //倒计时结束，关闭
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    [sender setTitle:@"发送验证码" forState:UIControlStateNormal];
                    sender.userInteractionEnabled = YES;
                });
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
            //网络链接失败
            //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [sender setTitle:@"发送验证码" forState:UIControlStateNormal];
                sender.userInteractionEnabled = YES;
            });
        }
        
    }];
}
- (void)handlePushColumn:(UITapGestureRecognizer *)tap {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)handleProtocal:(UITapGestureRecognizer *)tap {
    ISAACProtocalController *protocalVC = [[ISAACProtocalController alloc] init];
    [self pushViewController:protocalVC animate:YES];
}


- (void)handleConfirmLogin:(UIButton *)sender {
    if (_accountText.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        return;
    }
    if (![TTConfig validateMobile:_accountText.text]) {
        [SVProgressHUD showErrorWithStatus:@"手机号不正确"];
        return;
    }
    if (_pswText.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入验证码"];
        return;
    }
   
    ISAACRegistPSWController *vc = [[ISAACRegistPSWController alloc] init];
    vc.phone = _accountText.text;
    vc.verify_code = _pswText.text;
    [self pushViewController:vc animate:YES];
}


@end
